App({
  onLaunch() {
    // 初始化小程序
    console.log('小程序启动')
    
    // 初始化用户信息
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.globalData.userInfo = userInfo
    }
    
    // 初始化购物车数据
    const cart = wx.getStorageSync('cart') || []
    this.globalData.cart = cart
    
    // 初始化浏览记录
    const browsingHistory = wx.getStorageSync('browsingHistory') || []
    this.globalData.browsingHistory = browsingHistory
    
    // 初始化收藏
    const favorites = wx.getStorageSync('favorites') || []
    this.globalData.favorites = favorites
  },
  
  globalData: {
    userInfo: null,
    cart: [],
    browsingHistory: [],
    favorites: [],
    orders: [],
    targetOrderStatus: null // 用于从其他页面跳转到订单列表时指定要显示的状态
  },
  
  // 添加到购物车
  addToCart(product) {
    const cart = this.globalData.cart
    const existingItem = cart.find(item => item.id === product.id && item.date === product.date)
    
    if (existingItem) {
      existingItem.quantity += product.quantity || 1
    } else {
      cart.push({
        ...product,
        quantity: product.quantity || 1,
        selected: true
      })
    }
    
    this.globalData.cart = cart
    wx.setStorageSync('cart', cart)
    return cart
  },
  
  // 添加到浏览记录
  addToBrowsingHistory(product) {
    const history = this.globalData.browsingHistory
    const now = new Date()
    const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
    
    // 移除同一天相同的产品
    const filtered = history.filter(item => !(item.date === today && item.id === product.id))
    
    filtered.unshift({
      ...product,
      date: today
    })
    
    // 只保留最近30条
    this.globalData.browsingHistory = filtered.slice(0, 30)
    wx.setStorageSync('browsingHistory', this.globalData.browsingHistory)
  },
  
  // 添加到收藏
  addToFavorites(product) {
    const favorites = this.globalData.favorites
    if (!favorites.find(item => item.id === product.id)) {
      favorites.push(product)
      this.globalData.favorites = favorites
      wx.setStorageSync('favorites', favorites)
      return true
    }
    return false
  },
  
  // 移除收藏
  removeFromFavorites(productId) {
    const favorites = this.globalData.favorites
    this.globalData.favorites = favorites.filter(item => item.id !== productId)
    wx.setStorageSync('favorites', this.globalData.favorites)
  },
  
  // 检查是否已收藏
  isFavorite(productId) {
    return this.globalData.favorites.some(item => item.id === productId)
  }
})

